const { defineConfig } = require("@vue/cli-service");
const AutoImport = require("unplugin-auto-import/webpack");
const Components = require("unplugin-vue-components/webpack");
const CompressionPlugin = require("compression-webpack-plugin");
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const path = require("path");
const { resolve } = require('path');
// const TerserPlugin = require('terser-webpack-plugin');
const { name } = require('./package');

let fs = require("fs");


module.exports = defineConfig({
  lintOnSave: false, // es-lint代码规范检查开关 true: 开启 | false: 关闭
  // publicPath: '/child/homepage/',
  // publicpath只会在生产环境下起作用，开发环境不起作用
  publicPath: process.env.NODE_ENV === "development" ? "./" : "/child/homeBed/",
  transpileDependencies: true,
  configureWebpack() {
    return {
      name: process.env.VUE_APP_TITLE,
      resolve: {
        alias: {
          '@': resolve('src'),
          // '*': resolve(''),
          Assets: resolve('src/assets'),
        },
      },
      output: {
        library: `${name}-[name]`,
        libraryTarget: 'umd', // 把微应用打包成 umd 库格式
        chunkLoadingGlobal: `webpackJsonp_${name}`,
      },
      module: {
        rules: [
          {
            test: /\.(json5?|ya?ml)$/, // target json, json5, yaml and yml files
            loader: '@intlify/vue-i18n-loader',
            include: [
              // Use `Rule.include` to specify the files of locale messages to be pre-compiled
              path.resolve(__dirname, 'src/lang'),
            ],
          },
        ],
      },
      /*optimization: {
        minimize: true,
        minimizer: [
          new TerserPlugin({
            terserOptions: {
              compress: {
                drop_console: false, // 默认false，设置为true, 则会删除所有console.* 相关的代码。
                pure_funcs: ["console.log"], // 单纯禁用console.log
              }
            }
          })
        ]
      },*/
      optimization: {
        minimize: true,
        splitChunks: {
          chunks: 'all',
          minSize: 20000,
          maxSize: 244000,
          minChunks: 1,
          maxAsyncRequests: 30,
          maxInitialRequests: 30,
          automaticNameDelimiter: '~',
          cacheGroups: {
            vendors: {
              test: /[\\/]node_modules[\\/]/,
              name(module, chunks, cacheGroupKey) {
                if (!module.context) {
                  return `${cacheGroupKey}-unknown`;
                }
                const packageNameMatch = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/);
                const packageName = packageNameMatch ? packageNameMatch[1] : 'unknown';
                return `${cacheGroupKey}-${packageName.replace('@', '')}`;
              },
              priority: -10,
              chunks: 'all',
            },
            default: {
              minChunks: 2,
              priority: -20,
              reuseExistingChunk: true,
            },
          },
        },
      },
      plugins: [
        AutoImport({
          imports: ["vue", "vue-router", "pinia"],
          dts: true,
        }),
        Components({
          dts: true,
        }),
        // http://doc.ruoyi.vip/ruoyi-vue/other/faq.html#使用gzip解压缩静态文件
        new CompressionPlugin({
          test: /\.(js|css|html)?$/i, // 压缩文件格式
          filename: "[path][base].gz", // 压缩后的文件名
          algorithm: "gzip", // 使用gzip压缩
          minRatio: 0.8, // 压缩率小于1才会压缩
          threshold: 10240, // 小于10KB就不进行压缩
          // deleteOriginalAssets: true, // 删除源文件
        }),
        new MiniCssExtractPlugin({
          filename: '[name].[contenthash].css',
        }),
      ],
      devtool: "source-map",
    }
  },
  chainWebpack: (config) => {
    // set svg-sprite-loader
    config.module
      .rule("svg")
      .exclude.add(path.resolve(process.cwd(), "src/assets/icons"))
      .end();
    config.module
      .rule("icons")
      .test(/\.svg$/)
      .include.add(path.resolve(process.cwd(), "src/assets/icons"))
      .end()
      .use("svg-sprite-loader")
      .loader("svg-sprite-loader")
      .options({
        symbolId: "icon-[name]",
      })
      .end();
    if (process.env.NODE_ENV === 'production') {
      // 去除console.log输出
      config.optimization.minimizer('terser').tap((args) => {
        Object.assign(args[0].terserOptions.compress, {
          warnings: false, //默认false
          drop_console: true,
          drop_debugger: true, //默认true
          pure_funcs: ['console.log'],
        })
        return args
      });
    }
  },
  devServer: {
    port: 25050,
    /*https: {
      key: fs.readFileSync('./certs/localhost+5-key.pem'),
      cert: fs.readFileSync('./certs/localhost+5.pem')
    },
    https: true,*/
    hot: true,
    open: false,
    proxy: {
      // detail: https://cli.vuejs.org/config/#devserver-proxy
      [process.env.VUE_APP_BASE_API]: {
        target: process.env.VUE_APP_PROXY_TARGET,
        changeOrigin: true,
        pathRewrite: { ["^" + process.env.VUE_APP_BASE_API]: "" },
      },
    },
    headers: {
      "Access-Control-Allow-Origin": "*",
    },
  },
});

/*const { name } = require("./package.json");
const { defineConfig } = require("@vue/cli-service");

module.exports = defineConfig({
  transpileDependencies: true,
  devServer: {
    port: 9999, // 指定端口
    headers: {
      "Access-Control-Allow-Origin": "*", // 配置跨域
      "Access-Control-Allow-Headers": "*",
      "Access-Control-Allow-Credentials": "true",
      "Access-Control-Allow-Methods": "*",
      "Cache-Control": "no-cache",
    },
    client: {
      overlay: {
        errors: true,
        warnings: false,
      }
    },
  },
  configureWebpack: {
    output: {
      library: `${name}-[name]`,
      libraryTarget: "umd",
      chunkLoadingGlobal: `webpackJsonp_${name}`,
    }
  },
});*/
